import { defineComponent,h, watch, ref, onMounted, onUnmounted } from '@vue/runtime-core'
import planeImg from '../../assets/plane.png'
import { game } from '../Game'

export const myPlaneInfo = {
    width: 258,
    height: 364
}
export default defineComponent({
    props: ['x', 'y'],
    setup(props, ctx){
        const x = ref(props.x)
        const y = ref(props.y)
        watch(props, (oldValue,newValue) => {
            x.value = newValue.x
            y.value = newValue.y
        })
        //发射子弹，子弹数据由此产生，所以在此注册事件
        let isAttack = false
        const ATTACK_INTERVAL = 10//攻击间隔时间
        let startTime = 0
        const startAttack = (e) => {
            if (e.code === 'Space') {
                isAttack = true
                startTime = 100
            }
        }
        const stopAttack = (e) => {
            if (e.code === 'Space') {
                isAttack = false
            }
        }

        const handleTicker = () => {
            if (isAttack) {
                startTime++
                if (startTime > ATTACK_INTERVAL) {
                    ctx.emit('attack', {
                        x: x.value + 106,
                        y: y.value
                    })
                    startTime = 0
                }
            }   
        }
        onMounted(() =>{
            game.ticker.add(handleTicker)
            window.addEventListener('keydown', startAttack)
            window.addEventListener('keyup', stopAttack)
        })
        onUnmounted(() => {
            game.ticker.remove(handleTicker)
            window.removeEventListener('keydown', startAttack)
            window.removeEventListener('keyup', stopAttack)
        })
      
        return { x, y }
    },
    render(ctx){
        return h('Sprite',{
            x: ctx.x,
            y: ctx.y,
            texture: planeImg
        })
    }
})